package com.task.submitter.controllers;

import java.util.Calendar;
import java.util.List;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.task.submitter.dto.VoltageTaskRequest;
import com.task.submitter.tasks.VoltageFluxData;
import com.task.submitter.tasks.VoltageFluxService;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.repackaged.com.google.api.client.util.Lists;
import com.google.gson.Gson;


@Controller
public class VoltageTaskFluxController extends BaseController {

	@Autowired
	private VoltageFluxService voltageService;
	
	@ResponseBody
	@RequestMapping("/submit/voltagetask")
	public void processVoltageFlux(@ModelAttribute VoltageTaskRequest request){
		VoltageFluxData data = voltageService.processVoltageFluxTask(request.getDim(), request.getTemperature(), request.getSteps());
		
		List<List<Double>> matrix = Lists.newArrayList();
		for (int row = 0; row < data.getrDimension(); row++) {
			List<Double> dataRow = Lists.newArrayList();
			matrix.add(dataRow);
			for (int col = 0; col < data.getrDimension(); col++) {
				dataRow.add(data.getrGrid()[row][col]);
			}
		}
		
		Gson gson = new Gson();
		String jsonMatrix = gson.toJson(matrix);
		Text text = new Text(jsonMatrix);
		
		Key userCtxKey = KeyFactory.createKey("UserContext", request.getUser());
		
		Entity flux = new Entity("Flux", userCtxKey);
		flux.setProperty("name", RandomStringUtils.randomAlphabetic(64));
		flux.setProperty("data", text);
		flux.setProperty("dim", data.getrDimension());
		flux.setProperty("steps", request.getSteps());
		flux.setProperty("temperature", request.getTemperature());
		flux.setProperty("date", Calendar.getInstance().getTime());
		
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		datastore.put(flux);
		
	}
	
}
